//
//  UIViewController+JFBase.m
//  JFBase
//
//  Created by Alan Wang on 2019/4/17.
//  Copyright © 2019 Alan Wang. All rights reserved.
//

#import "UIViewController+JFBase.h"
#import <objc/runtime.h>

#import "JFNetCheck.h"
#import "JFMacro.h"
#import "UINavigationBar+handle.h"
#import "UINavigationController+JFNavAttribute.h"
#import "JFBaseNavigationController.h"
#import "UIImage+BaseBuddle.h"
#import "UINavigationItem+FastItem.h"
#import "JFBase.h"
#import <PPBadgeView.h>




static char *JF_ControlName = "AW_JF_ControlName";
static char *JF_UserInfo = "AW_JF_UserInfo";
static char *JF_CallBack = "AW_JF_CallBack";
static char *JF_Notedict = "AW_JF_Notedict";
static char *JF_BaseEnable = "AW_JF_BaseEnable";

static char *JF_GES_GOBACK = "JF_GES_GOBACK";



@implementation UIViewController (JFBase)

+ (void)swizzleMethod:(SEL)origSelector withMethod:(SEL)newSelector {
    Class class = self;
    
    Method originalMethod = class_getInstanceMethod(class, origSelector);
    Method swizzledMethod = class_getInstanceMethod(class, newSelector);
    
    BOOL didAddMethod = class_addMethod(class,
                                        origSelector,
                                        method_getImplementation(swizzledMethod),
                                        method_getTypeEncoding(swizzledMethod));
    if (didAddMethod) {
        class_replaceMethod(class,
                            newSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}


+(void)load{
    
    [UIViewController swizzleMethod:@selector(loadView) withMethod:@selector(aop_loadView)];
    [UIViewController swizzleMethod:@selector(viewDidLoad) withMethod:@selector(aop_viewDidLoad)];
    [UIViewController swizzleMethod:@selector(viewWillAppear:) withMethod:@selector(aop_viewWillAppear:)];
    [UIViewController swizzleMethod:@selector(viewWillDisappear:) withMethod:@selector(aop_viewWillDisappear:)];
    
    
    [UIViewController swizzleMethod:@selector(shouldAutorotateToInterfaceOrientation:) withMethod:@selector(aop_shouldAutorotateToInterfaceOrientation:)];
    [UIViewController swizzleMethod:@selector(supportedInterfaceOrientations) withMethod:@selector(aop_supportedInterfaceOrientations)];
    [UIViewController swizzleMethod:@selector(preferredInterfaceOrientationForPresentation) withMethod:@selector(aop_preferredInterfaceOrientationForPresentation)];
}

#pragma mark - 锁死竖直方向
- (BOOL)aop_shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return (toInterfaceOrientation == UIInterfaceOrientationMaskPortrait);
}

- (UIInterfaceOrientationMask)aop_supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)aop_preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationPortrait;
}

#pragma mark--辅助方法
-(void)aop_loadView{
 
    if(!self.baseEnable){
        if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)])
        {
            [self setEdgesForExtendedLayout:UIRectEdgeNone];
        }
        if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0))
        {
            self.navigationController.navigationBar.translucent = NO;
        }
    }

    [self aop_loadView];
}

-(void)aop_viewWillDisappear:(BOOL)animated{
    [self aop_viewWillDisappear:animated];
//    if (self.gesdelegate) {
//       self.navigationController.interactivePopGestureRecognizer.delegate = self.gesdelegate;
//    }
  
}
-(void)aop_viewWillAppear:(BOOL)animated{
    
    if(!self.baseEnable){
        if([self respondsToSelector:@selector(isHideNav)]){//实现了就处理 没实现就不管了
            BOOL flag = [self isHideNav];
            self.navigationController.navigationBar.hidden = flag;
        }else{
            self.navigationController.navigationBar.hidden = NO;
        }
        
        //设置导航栏底部线的颜色

        if([self respondsToSelector:@selector(navLineColor)]){//实现了就设置当前的背景色
            UIColor *  color = [self navLineColor];
              [self.navigationController.navigationBar navBarBootomLineColor:color];
        }else{//设置默认的颜色
            UIColor * colornNavBottomLine = AWThemeColorForKey(@"Global.navBgColor");// [UIColor 
            [self.navigationController.navigationBar navBarBootomLineColor:colornNavBottomLine];
        }
        
        
        //设置导航栏颜色
        if([self respondsToSelector:@selector(navBackGroundColor)]){//实现了就设置当前的背景色
            UIColor *  color = [self navBackGroundColor];
            [self.navigationController.navigationBar navBarBackGroundColor:color image:nil isOpaque:YES];
        }else{//设置默认的颜色
            UIColor * colot = [self.navigationController navBackGroundColor];
            [self.navigationController.navigationBar navBarBackGroundColor:colot image:nil isOpaque:YES];
        }
       
        
        if([self respondsToSelector:@selector(isHideNavBootomLine)]){//实现了就设置当前的背景色
            BOOL flag = [self isHideNavBootomLine];
            [self.navigationController.navigationBar navBarBottomLineHidden:flag];
        }
        
        if([self respondsToSelector:@selector(barStyle)]){//实现了就设置当前的背景色
            UIBarStyle style = [self barStyle];
            if (style == 0) {
                
                if(@available(iOS 13.0, *)) {
                    self.navigationController.navigationBar.barStyle = 3;
                    [UIApplication sharedApplication].statusBarStyle = 3;
                }else{
                    self.navigationController.navigationBar.barStyle = style;
                    [UIApplication sharedApplication].statusBarStyle = style;
                }
            }else{
                self.navigationController.navigationBar.barStyle = style;
                [UIApplication sharedApplication].statusBarStyle = style;
            }
        
     
        }else{//没有实现的话就使用默认的
            if ([self isKindOfClass:[UINavigationController class]]) {
                UINavigationController * vc = (UINavigationController*)self;
                UIBarStyle style  = [vc navBarStyle];
                
                if (style == 0) {
                        
                        if(@available(iOS 13.0, *)) {
                            self.navigationController.navigationBar.barStyle = 3;
                            [UIApplication sharedApplication].statusBarStyle = 3;
                        }else{
                            self.navigationController.navigationBar.barStyle = style;
                            [UIApplication sharedApplication].statusBarStyle = style;
                        }
                    }else{
                        self.navigationController.navigationBar.barStyle = style;
                        [UIApplication sharedApplication].statusBarStyle = style;
                    }
                
            }else{
                if(self.navigationController){
                    UIBarStyle style  = [self.navigationController navBarStyle];
                       if (style == 0) {
                            if(@available(iOS 13.0, *)) {
                                self.navigationController.navigationBar.barStyle = 3;
                                [UIApplication sharedApplication].statusBarStyle = 3;
                            }else{
                                self.navigationController.navigationBar.barStyle = style;
                                [UIApplication sharedApplication].statusBarStyle = style;
                            }
                        }else{
                            self.navigationController.navigationBar.barStyle = style;
                            [UIApplication sharedApplication].statusBarStyle = style;
                        }
                }
            }
        }
        
        
        if([self respondsToSelector:@selector(navTintColor)]){//实现了就设置当前的背景色
            UIColor *  color = [self navTintColor];
            self.navigationController.navigationBar.tintColor = color;
            self.navigationController.navigationBar.barTintColor = color;
            [[UINavigationBar appearance] setTintColor:color];
            [self.navigationItem.rightBarButtonItem setTintColor:color];
            [self.navigationItem.leftBarButtonItem setTintColor:color];
            [self.navigationController.navigationBar setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
                                                                              color,NSForegroundColorAttributeName,[UIFont fontWithName:@"PingFangSC-Medium" size:17.f],NSFontAttributeName,nil]];
        }else{//设置默认的颜色
            
            if([self.navigationController respondsToSelector:@selector(navTintColor)]){//实现了就设置当前的背景色
                UIColor *  color = [self.navigationController navTintColor];
                self.navigationController.navigationBar.tintColor = color;
                self.navigationController.navigationBar.barTintColor = color;
                [[UINavigationBar appearance] setTintColor:color];
                [self.navigationItem.rightBarButtonItem setTintColor:color];
                [self.navigationItem.leftBarButtonItem setTintColor:color];
                [self.navigationController.navigationBar setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
                                                                                  color,NSForegroundColorAttributeName,[UIFont fontWithName:@"PingFangSC-Medium" size:17.f],NSFontAttributeName,nil]];
            }else{//设置默认的颜色
                UIColor *  color = HexColor(@"#ffffff");
                self.navigationController.navigationBar.tintColor = color;
                 self.navigationController.navigationBar.barTintColor = color;
                [[UINavigationBar appearance] setTintColor:color];
                [self.navigationItem.rightBarButtonItem setTintColor:color];
                [self.navigationItem.leftBarButtonItem setTintColor:color];
                [self.navigationController.navigationBar setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
                                                                                  color,NSForegroundColorAttributeName,[UIFont fontWithName:@"PingFangSC-Medium" size:17.f],NSFontAttributeName,nil]];
            }
        }
        
        if (self.navigationController.viewControllers.count > 1) {
            if (!self.navigationItem.leftBarButtonItem) {
                NSString * imageName = @"return";
               
                UIImage * image = [UIImage imageNamed:imageName] ;
                
                
      
                
//                UIButton * button = [self.navigationItem creatBtn];
//                [self.navigationItem setLeftImage:button image:image];
//                [button setTitleColor:HexColor(@"#ffffff") forState:UIControlStateNormal];
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                button.frame = CGRectMake(0, 0, image.size.width, image.size.height);
                [button setImage:image forState:UIControlStateNormal];
                [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
                UIBarButtonItem * backBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
                self.navigationItem.leftBarButtonItem = backBarButtonItem; 
            }else{
                UIBarButtonItem * leftBarButtonItem = self.navigationItem.leftBarButtonItem;
                if (leftBarButtonItem.customView && [leftBarButtonItem.customView isKindOfClass:[UIButton class]] && leftBarButtonItem.customView.tag == 4444) {
                    NSString * imageName = @"return";
                    if ([@"White" isEqualToString:[AWThemeManager shareInstance].skinName]) {
                        imageName = @"return";
                    }
                    UIImage * image = [UIImage imageNamed:imageName];
                    UIButton * button = [self.navigationItem creatBtn];
                    [self.navigationItem setLeftImage:button image:image];
                    [button setTitleColor:HexColor(@"#ffffff") forState:UIControlStateNormal];
                    [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
                    UIBarButtonItem * backBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
                    self.navigationItem.leftBarButtonItem = backBarButtonItem;
                } 
            }
   
        }  
    }
        if (self.navigationController.viewControllers.count > 1) {
            self.navigationController.interactivePopGestureRecognizer.delegate = self;
        }




    
    [self aop_viewWillAppear:animated];
    

    

    
}
//当前需要的返回图片
-(UIImage*)backImage{
    NSString * imageName = @"topbtn_back";
    if ([@"White" isEqualToString:[AWThemeManager shareInstance].skinName]) {
        imageName = @"topbtn_back_w";
    }
    UIImage * image = [UIImage imageNameFromBaseBuddle:imageName];
    return image;
}
-(UIImage*)shareImage{
    NSString * imageName = @"分享";
    if ([@"White" isEqualToString:[AWThemeManager shareInstance].skinName]) {
        imageName = @"分享w";
    }
    UIImage * image = [UIImage imageNameFromBaseBuddle:imageName];
    return image;
}
-(UIBarButtonItem*)msgLeftItem{
    JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
    msg.from = @"BASE";
    msg.to = @"APP";
    msg.requestNum = @"000013";
    JFMsgCenterVo* data = [JFMsgCenteManager requestWithMsgCenterVo:msg callback:nil];
    NSInteger msgCount = [data.params integerForKey:@"msgCount"];
    UIImage * image = (UIImage*)data.params[@"image"];
    UIBarButtonItem* leftItem =  [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(goMsg:)];
    self.navigationItem.leftBarButtonItem = leftItem;
    return leftItem;
}
//设置右侧侧消息按钮
-(UIBarButtonItem*)msgRightItem{
    JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
    msg.from = @"BASE";
    msg.to = @"APP";
    msg.requestNum = @"000013";
    JFMsgCenterVo* data = [JFMsgCenteManager requestWithMsgCenterVo:msg callback:nil];
    NSInteger msgCount = [data.params integerForKey:@"msgCount"];
    UIImage * image = (UIImage*)data.params[@"image"];
    UIBarButtonItem* leftItem =  [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(goMsg:)];
    self.navigationItem.rightBarButtonItem = leftItem;
    return leftItem;
}

-(void)goMsg:(id)sender{
    JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
    msg.from = @"BASE";
    msg.to = @"USER";
    msg.requestNum = @"400029";
    [JFMsgCenteManager requestWithMsgCenterVo:msg callback:nil];
}


-(void)aop_viewDidLoad{

}
#pragma mark--扩展方法
-(void)listenNotification:(NSString*)notiName{
    if (![self notedict]) {
        [self setNotedict:[[NSMutableDictionary alloc] init]];
        [[self notedict] setValue:notiName forKey:notiName];
        [self setNoti:notiName];
    }else{
        NSArray * allKey=[self notedict].allKeys;
        if (allKey&&allKey.count) {
            if (![allKey containsObject:notiName]) {
                [[self notedict] setValue:notiName forKey:notiName];
                [self setNoti:notiName];
            }
        }else{
            [[self notedict] setValue:notiName forKey:notiName];
            [self setNoti:notiName];
        }
    }
}
-(void)listenNotificationWithArr:(NSArray*)notiNameArr{
    for (NSString*notiname in notiNameArr) {
        [self listenNotification:notiname];
    }
}
//当前已经监听的通知
-(NSArray*)listenedNotification{
    NSArray * noti =@[];
    if([self notedict]){
        noti = [[self notedict] allKeys];
    }
    return noti;
}
-(void)notificationCenter:(NSNotification*)noti{
    if([AW_NETWORKCHANGE isEqualToString:noti.name]){
        NetStatus state = [noti.object integerValue];
        switch (state) {
            case NetStatus_Unknown:
                break;
            case NetStatus_NotReachable:
                break;
                
            default:
                break;
        }
    }
}

-(void)setNoti:(NSString*)name{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationCenter:) name:name object:nil];
}

//底层实现的返回函数
-(void)back{
    UINavigationController * nav =self.navigationController;
    if([nav isKindOfClass:[JFBaseNavigationController class]]){
        JFBaseNavigationController * navb = (JFBaseNavigationController*)self.navigationController;
        [navb popViewController];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}
//- (UIStatusBarStyle)preferredStatusBarStyle {
//    if([self respondsToSelector:@selector(barStyle)]){//实现了就设置当前的背景色
//        UIBarStyle style = [self barStyle];
//        return (UIStatusBarStyle)style;
//    }else{//没有实现的话就使用默认的
//        UIBarStyle style  = [self.navigationController navBarStyle];
//         return (UIStatusBarStyle)style;
//    }
//}


/**
 获取当前正在显示的界面
 
 @param rootViewController UIViewController description
 @return return value description
 */
+ (UIViewController *)topViewController:(UIViewController *)rootViewController
{
    UIViewController *topViewController = rootViewController;
    if (topViewController.presentedViewController) {
        return [self topViewController:topViewController.presentedViewController];
    }
    if ([topViewController isKindOfClass:[UINavigationController class]]) {
        return [self topViewController:((UINavigationController *)topViewController).viewControllers.lastObject];
    }
    if ([topViewController isKindOfClass:[UITabBarController class]]) {
        return [self topViewController:((UITabBarController *)topViewController).selectedViewController];
    }
    return topViewController;
}

/**
 当前的viewController
 
 @return return value description
 */
+(UIViewController *)topViewController
{
    UIViewController * currentController;
    UIWindow * window= [UIApplication sharedApplication].keyWindow;
    UIViewController * windowRootVC = window.rootViewController;
    
    currentController = [self topViewController:windowRootVC];
    return currentController;
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    return self.navigationController.viewControllers.count > 1;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return self.navigationController.viewControllers.count > 1;
}

#pragma mark--扩展属性
-(void)setCallBack:(baseCallBack)callBack{
    
      objc_setAssociatedObject(self, &JF_CallBack, callBack, OBJC_ASSOCIATION_COPY);
}
-(baseCallBack)callBack{
    return objc_getAssociatedObject(self, &JF_CallBack);
}
-(void)setControlName:(NSString *)controlName{
      objc_setAssociatedObject(self, &JF_ControlName, controlName, OBJC_ASSOCIATION_COPY);
}
-(NSString*)controlName{
    
     return objc_getAssociatedObject(self, &JF_ControlName);
}

-(void)setUserInfo:(NSMutableDictionary *)userInfo{
     objc_setAssociatedObject(self, &JF_UserInfo, userInfo, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSMutableDictionary*)userInfo{
      return objc_getAssociatedObject(self, &JF_UserInfo);
}

-(void)setNotedict:(NSMutableDictionary *)notedict{
    objc_setAssociatedObject(self, &JF_Notedict, notedict, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSMutableDictionary*)notedict{
    return objc_getAssociatedObject(self, &JF_Notedict);
}

-(void)setBaseEnable:(BOOL)baseEnable{
    
     objc_setAssociatedObject(self, &JF_BaseEnable,[NSNumber numberWithBool:baseEnable], OBJC_ASSOCIATION_ASSIGN);
}
-(BOOL)baseEnable{
      return [objc_getAssociatedObject(self, &JF_BaseEnable) boolValue];
}

//-(void)setGesdelegate:(id<UIGestureRecognizerDelegate>)gesdelegate{
////      objc_setAssociatedObject(self, &JF_GES_GOBACK,gesdelegate, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
//    objc_setAssociatedObject(self, &JF_GES_GOBACK,gesdelegate, OBJC_ASSOCIATION_ASSIGN);
//}
//-(id<UIGestureRecognizerDelegate>)gesdelegate{
//      return objc_getAssociatedObject(self, &JF_GES_GOBACK);
//}
@end
